-- FUNCTION: public.widget_PieChart_Pharmacy_FrequentlyBroughtProducts(date, text)

-- DROP FUNCTION public."widget_PieChart_Pharmacy_FrequentlyBroughtProducts"(date, text);

CREATE OR REPLACE FUNCTION public."widget_PieChart_Pharmacy_FrequentlyBroughtProducts"(
	"fromDate" date,
	"filterType" text)
    RETURNS TABLE("Date" date, "Name" text, "Count" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
declare
--f record;
--filtervalue interval;
--intervaldata interval;

f record;
intervaldata interval;
ftype text;
currentdate date;
fromdate date;
begin
intervaldata:= case when "filterType"='day' then '1 D' when "filterType"='month' then '1 Month' when "filterType"='year' then '1 Year' end;
ftype:= case when "filterType"='day' then 'month'::text  when "filterType"='month' then 'year'::text when "filterType"='year' then 'year'::text end;
currentdate:= case when  "filterType"='year' then date_trunc(ftype, "fromDate")  - '2 Y'::interval else date_trunc(ftype, "fromDate") end ;
fromdate:=case when "filterType"='day' and  current_date > "fromDate"  then   (date_trunc('month', "fromDate"::date) + interval '1 month' - interval '1 day')::date
 when  "filterType"='month' and   "fromDate" < current_date then  date_trunc('Year', "fromDate"::date) + interval '1 Year' - interval '1 month' 
 
else "fromDate" end;

 raise notice 'intervaldata %', intervaldata;
 raise notice 'ftype %', ftype;
  raise notice 'currentdate %', currentdate;
create  Temp TABLE temp_table 
(
	startdate date,
   	enddate date, 
	dname text,
  	countdata numeric
 ) ON COMMIT DELETE ROWS;
 
create  Temp TABLE temp_date_table 
( startdate date,
   enddate date
 ) ON COMMIT DELETE ROWS;
 for f in 
 select   generate_series( currentdate  , fromdate,  intervaldata)  weeks 
    loop 
           insert into temp_date_table (startdate,enddate)
		   select f.weeks::text::date ,(f.weeks+ intervaldata)::text::date ;
		   --raise notice 'datetable %', f.weeks::text::date;
   end loop;
for f in 
 select   generate_series( currentdate  , fromdate,  intervaldata)  weeks 
    loop 
	raise notice 'currentdate %', f.weeks::text::date;
	raise notice 'fromdate %', fromdate::date;
	insert into temp_table (startdate,enddate,dname,countdata)
----------------------------

with saleData as (
	select PP."PharmacyProductId", count(PP."PharmacyProductId") "Count", PP."ProductName",PP."GenericName",ci."Name" "CategoryName",sum(PPD."Quantity") 
from "PharmacyPurchaseHeader" PH
		join "Supplier" s on s."SupplierId"=ph."SupplierId"
		join "PharmacyPurchaseDetail" ppd on ppd."PharmacyPurchaseHeaderId" = ph."PharmacyPurchaseHeaderId"
		join "PharmacyProduct" pp on pp."PharmacyProductId" = ppd."PharmacyProductId"
		join "LookupValue" ci on ci."LookupValueId"=pp."CategoryId"
		join "Account" A on A."AccountId"=ph."CreatedBy"
		join "Role" R on R."RoleId"=A."RoleId"
		left join "PharmacyPurchaseReturnHeader" pr on pr."PharmacyPurchaseHeaderId" = PH."PharmacyPurchaseHeaderId"
	where   PH."CreatedDate"::date >= f.weeks::text::date and PH."CreatedDate"::date <= (f.weeks+ intervaldata)::text::date  
	--       case when "fromDate" is null then 1=1 else PH."BillDate"::date >= "fromDate" end 
	-- 	and case when "toDate" is null then 1=1 else PH."BillDate"::date <= "toDate" end 
	group by PP."PharmacyProductId",PP."ProductName",PP."GenericName",ci."Name" 
order by "Count"  desc 
	--limit 20
	)
	

----------------------------
select date_trunc('month', current_date)::date startdate ,f.weeks enddate, sd."ProductName",sd."Count"
	from saleData sd;
end loop;
	RETURN QUERY
	
	with saleData as (select A.endDate,A.dname,sum(coalesce(A.countdata,0) )::numeric countdata from temp_table A group by A.endDate,A.dname)
	
-- 	select A.startdate,B.dname,coalesce(B.countdata,0) from temp_date_table A
-- 	left join finalData B on A.startdate=B.endDate 
-- 	order by "Count" desc;
	
	select A.startdate,B.dname,coalesce(B.countdata,0) as "Count" from saleData B
	 left join   temp_date_table A on A.startdate=B.endDate 
	 order by "Count" desc 
	 limit 20;
	 
	drop table temp_table;
	drop table temp_date_table;				
END;
$BODY$;

ALTER FUNCTION public."widget_PieChart_Pharmacy_FrequentlyBroughtProducts"(date, text)
    OWNER TO postgres;
